'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 给好友送赞
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var PlayerManager = require('../../../../libs/playerManager');
var constantUtil = require('../../../../util/constantUtil');
var roleService = require('../../../../services/roleService');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var friend_role_id = msg.friend_role_id;
    var energy_list = [];

    if (!friend_role_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'friend', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var friend_model = player_manager.friend;

                // 收取赠送体力是否超过次数上限
                if (friend_model.getTodayReceiveNum() >= constantUtil.value('friend_sp_times')) {
                    return next(null, {
                        code: Code.FRIEND_TODAY_RECEIVE_MAX
                    });
                }

                // 收取赠送的体力
                if (!friend_model.removePresent(friend_role_id)) {
                    return next(null, {
                        code: Code.FRIEND_HAVE_NOT_PRESENT
                    });
                }

                energy_list.push({
                    reward: 0,
                    reward_type: 15,
                    reward_num: constantUtil.value('friend_sp_num'),
                    hole_num: 0,
                    reward_value: 0
                });

                // 增加友情值
                // 增加体力
                var add_energy = constantUtil.value('friend_sp_num');
                roleService.addEnergy(player_manager, moduleType.MDL_OTHER, operationType.OPR_OTHER_RECEIVE_ENERGY, add_energy);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    energy_list: energy_list
                }
            });
        }
    );
};
